﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NoodlesCms.Configuration;
using Noodles.Core.Repositories;
using Noodles.Core.Model;

namespace NoodlesCms.Areas.Admin.Controllers
{
    public class PagesController : Controller
    {
        //
        // GET: /Admin/Pages/
        public INoodlesRepository noodlesRepo { get; set; }
        public ActionResult Index()
        {
            return View();
        }
        [ChildActionOnly]
        public ActionResult PageList()
        {
            IEnumerable<Pages> pagelist = noodlesRepo.GetPages();
            return PartialView(pagelist);
        }
        [HttpGet]
        public ActionResult PageNew()
        {
            Pages newPageModel = new Pages();
            return PartialView(newPageModel);
        }

        [HttpPost]
        public ActionResult PageNew(Pages page)
        {
            if (page.PageName != "")
            {
                page.CreateDate = DateTime.Now;
                page.UpdateDate = DateTime.Now;
                var pageRepository = DependencyResolver.Current.GetService<Noodles.Core.Repositories.IRepository>();
                pageRepository.Add(page);
                TempData["message"] = "Page Added Successfully !";
            }
            return RedirectToAction("Index", "Pages");
        }
        [HttpGet]
        public ActionResult EditPage(int id, FormCollection collection)
        {
            var pageRepository = DependencyResolver.Current.GetService<Noodles.Core.Repositories.IRepository>();
            Pages page = pageRepository.Get<Pages>(id);
            return PartialView("PageNew", page);
        }
        [HttpPost]
        public ActionResult EditPage(int id, Pages page)           
        {
            var pageRepository = DependencyResolver.Current.GetService<Noodles.Core.Repositories.IRepository>();
            var persistentPage = pageRepository.Get<Pages>(id);
            if (persistentPage == null)
            {
                throw new Exception(String.Format("Page with Id: {0} does not exist.", page.PageID));
            }
            persistentPage.PageName = page.PageName;
            persistentPage.PageDesc = page.PageDesc;

            pageRepository.Add(persistentPage); 
            TempData["message"] = "Page Saved Successfully !";
            return RedirectToAction("Index", "Pages");
        }

    }
}
